# main.py
from parser import parse_slow_query_log
from alert import send_alert


def process_new_slow_query(log_file_path):
    with open(log_file_path, 'r') as f:
        lines = f.readlines()

    # 找到最新的慢查询块（简化版）
    block = []
    for line in reversed(lines):  # 从后往前找
        if line.startswith("# Time:"):
            block.insert(0, line)
            break
        block.insert(0, line)

    # 解析
    tx = parse_slow_query_log(block)
    if tx and tx['duration_sec'] > 5:  # 只处理超过 5 秒的
        print("检测到长事务:", tx)

        # 这里你可以调用 AI 模型、发告警等
        fingerprint = f"long_tx_{int(tx['duration_sec'] / 10)}s_rows{tx['rows_affected']}"
        send_alert(f"🚨 长事务: {tx['duration_sec']:.1f}s, 影响{tx['rows_affected']}行", fingerprint)


# 运行
process_new_slow_query("/var/log/mysql/slow.log")